package com.vates.gestion.dao.impl;

import java.util.List;
import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import com.vates.gestion.dao.BaseDao;
import com.vates.gestion.entidades.Cliente;

@Repository(value = "clienteDao")
public class ClienteDaoImpl implements BaseDao<Cliente> {

	private EntityManager em;

	/*
	 * Sets the entity manager
	 */

	@PersistenceContext
	public void setEntityManager(EntityManager em) {
		this.em = em;

	}

	@Override
	@Transactional(readOnly = false)
	public Cliente nuevo(Cliente entidad) {

		return em.merge(entidad);
	}

	@Transactional(readOnly = false)
	public Cliente modificar(Cliente cliente) {
		return em.merge(cliente);
	}

	@Override
	public Cliente buscarPorId(Long id) {

		return em.find(Cliente.class, id);

	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<Cliente> buscarTodos() {

		return em.createQuery("select c from Cliente c order by c.id")
				.getResultList();

	}

	@SuppressWarnings("unchecked")
	@Override
	@Transactional(readOnly = true)
	public List<Cliente> buscarPorNombre(String nombre) {

		return em
				.createQuery(
						"select c from Cliente c where c.nombre LIKE :nombre order by c.id")
				.setParameter("nombre", nombre).getResultList();

	}

	@Override
	@Transactional
	public void borrar(Cliente clienteEncontrado) {
		clienteEncontrado = em.find(Cliente.class, clienteEncontrado.getIdCliente());
		em.remove(clienteEncontrado);
	}

}